<template>
  <view class="pb-3 box-border" :style="{ height: `calc(100vh + ${store.$state.systemInfo.safeAreaInsets!.bottom}px)` }">
    <van-cell-group>
      <van-field
        required
        label="姓名"
        clearable
        :value="data.fullName"
        placeholder="请输入姓名"
        border="false"
        @change="
          (e: any) => {
            data.fullName = e.detail;
          }
        "
      />
      <van-field
        required
        label="手机号"
        clearable
        :value="data.phone"
        placeholder="请输入手机号"
        border="false"
        @change="
          (e: any) => {
            data.phone = e.detail;
          }
        "
      />
      <van-field
        required
        label="身份证"
        clearable
        :value="data.idCard"
        placeholder="请输入身份证"
        border="false"
        @change="
          (e: any) => {
            data.idCard = e.detail;
          }
        "
      />
      <van-field required label="银行" :value="data.bankName" is-link readonly placeholder="请选择银行" border="false" @click-input="goToBankList()" />
      <van-field required label="银行支行" v-if="data.bankName" is-link :value="data.branchName" readonly placeholder="请选择银行支行" border="false" @click-input="goToBankBranchList()" />
      <van-field
        required
        label="银行卡号"
        clearable
        :value="data.cardNo"
        placeholder="请输入银行卡号"
        border="false"
        @change="
          (e: any) => {
            data.cardNo = e.detail;
          }
        "
      />
      <van-field label="开通状态" v-if="data.openState">
        <view slot="input">
          <van-tag :type="filters.openStateFilter(data.openState)!.type">{{ filters.openStateFilter(data.openState)!.value }}</van-tag>
        </view>
      </van-field>
      <van-field label="启用状态" v-if="data.relationState">
        <view slot="input">
          <van-tag :type="filters.relationStateFilter(data.relationState)!.type">{{ filters.relationStateFilter(data.relationState)!.value }}</van-tag>
        </view>
      </van-field>
    </van-cell-group>
    <van-grid column-num="2" border="false">
      <van-grid-item use-slot>
        <view>身份证正面照</view>
        <view>
          <van-uploader accept="image" :max-count="1" @after-read="handleChooseImg($event, 'idCardFront')">
            <image v-if="!data.idCardFrontPath" class="img-size" src="https://pic.kanglailab.com/common/idCardFront.png" />
            <image v-else class="img-size" :src="data.idCardFrontPath" />
          </van-uploader>
        </view>
      </van-grid-item>
      <van-grid-item use-slot>
        <view>身份证反面照</view>
        <view>
          <van-uploader accept="image" :max-count="1" @after-read="handleChooseImg($event, 'idCardBack')">
            <image v-if="!data.idCardBackPath" class="img-size" src="https://pic.kanglailab.com/common/idCardBack.png" />
            <image v-else class="img-size" :src="data.idCardBackPath" />
          </van-uploader>
        </view>
      </van-grid-item>
      <van-grid-item use-slot>
        <view>银行卡正面照</view>
        <view>
          <van-uploader accept="image" :max-count="1" @after-read="handleChooseImg($event, 'bankCardFront')">
            <image v-if="!data.bankCardFrontPath" class="img-size" src="https://pic.kanglailab.com/common/bankCardFront.png" />
            <image v-else class="img-size" :src="data.bankCardFrontPath" />
          </van-uploader>
        </view>
      </van-grid-item>
      <van-grid-item use-slot>
        <view>银行卡反面照</view>
        <view>
          <van-uploader accept="image" :max-count="1" @after-read="handleChooseImg($event, 'bankCardBack')">
            <image v-if="!data.bankCardBackPath" class="img-size" src="https://pic.kanglailab.com/common/bankCardBack.png" />
            <image v-else class="img-size" :src="data.bankCardBackPath" />
          </van-uploader>
        </view>
      </van-grid-item>
    </van-grid>
    <view class="my-3 px-3 box-border">
      <van-button @click="submitInfo" color="#ffc300" block>提 交</van-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import filters from '@/utils/filters';
import Tools from '@/utils/tools';
import UserRequest from '@/request/userRequest';
import { onLoad } from '@dcloudio/uni-app';
import { useAppStore } from '@/store';
import useToast from '@/hooks/useToast';
import useModal from '@/hooks/useModal';
import { navigate } from '@/utils/navigate';

interface IData {
  fullName: string;
  phone?: string;
  idCard?: string;
  cardNo?: string;
  bankCode?: string;
  branchCode?: string;
  bankName: string;
  branchName: string;
  bankCardFront: string;
  bankCardBack: string;
  idCardFront: string;
  idCardBack: string;
  ymAccountId?: number;
  otherYmAccountId?: number;
  userId?: number;
  idCardFrontPath: string;
  idCardBackPath: string;
  bankCardFrontPath: string;
  bankCardBackPath: string;
  openState?: number;
  relationState?: number;
}

const data = reactive<IData>({
  fullName: '',
  phone: undefined,
  idCard: undefined,
  cardNo: undefined,
  bankCode: undefined,
  branchCode: undefined,
  bankName: '',
  branchName: '',
  bankCardFront: '',
  bankCardBack: '',
  idCardFront: '',
  idCardBack: '',
  ymAccountId: undefined,
  otherYmAccountId: undefined,
  userId: undefined,
  idCardFrontPath: '',
  idCardBackPath: '',
  bankCardFrontPath: '',
  bankCardBackPath: '',
  openState: undefined,
  relationState: undefined,
});

interface IFormField {
  key: string; // 字段的键
  msg: string; // 错误提示消息
  pattern?: Array<{ reg: RegExp; msg: string }>; // 可选的模式数组
}

const store = useAppStore();

const { userInfo } = store.$state;

const { showToast } = useToast();

const { showModal } = useModal();

onLoad(() => {
  getAccountInfo();
});

onShow(() => {
  let pages = getCurrentPages();
  let currPage = pages[pages.length - 1]; //当前页面
  if (currPage.$vm.branchCode) {
    data.branchCode = currPage.$vm.branchCode;
  }
  if (currPage.$vm.branchName) {
    data.branchName = currPage.$vm.branchName;
  }
  if (currPage.$vm.bankName) {
    data.bankName = currPage.$vm.bankName;
  }
  if (currPage.$vm.bankCode) {
    data.bankCode = currPage.$vm.bankCode;
  }
});

const getAccountInfo = () => {
  UserRequest.GetCurrentYmAccountInfo({
    userType: 3,
    userId: userInfo.userId,
    hasLoading: true,
  }).then((res) => {
    let resD = res.data;
    data.fullName = resD.fullName;
    data.phone = resD.phone;
    data.idCard = resD.idCard;
    data.bankCode = resD.bankCode;
    data.bankName = resD.bankName;
    data.branchCode = resD.branchCode;
    data.branchName = resD.branchName;
    data.cardNo = resD.cardNo;
    data.bankCardFront = resD.bankCardFront;
    data.bankCardBack = resD.bankCardBack;
    data.idCardFront = resD.idCardFront;
    data.idCardBack = resD.idCardBack;
    data.ymAccountId = resD.ymAccountId;
    data.otherYmAccountId = resD.otherYmAccountId;
    data.openState = resD.openState;
    data.relationState = resD.relationState;
    data.bankCardFrontPath = resD.bankCardFront;
    data.bankCardBackPath = resD.bankCardBack;
    data.idCardFrontPath = resD.idCardFront;
    data.idCardBackPath = resD.idCardBack;
  });
};

const handleChooseImg = async (event: any, type: string) => {
  const prop = type;
  const baseCode = await Tools.uniBase64FromFile(event.detail.file.tempFilePath);
  const tempPath = event.detail.file.tempFilePath;
  switch (prop) {
    case 'idCardFront':
      data.idCardFront = baseCode;
      data.idCardFrontPath = tempPath;
      break;
    case 'idCardBack':
      data.idCardBack = baseCode;
      data.idCardBackPath = tempPath;
      break;
    case 'bankCardFront':
      data.bankCardFront = baseCode;
      data.bankCardFrontPath = tempPath;
      break;
    case 'bankCardBack':
      data.bankCardBack = baseCode;
      data.bankCardBackPath = tempPath;
      break;
  }
};

const validate = (arr: IFormField[], data: IData) => {
  return !arr.find((item: any) => {
    const val = data[item.key as keyof IData];
    if (!val) {
      showToast(item.msg, 'error');
      return true;
    } else if (item.pattern) {
      const val2 = item.pattern.find((item2: any) => !item2.reg.test(val));
      if (val2) {
        showToast(val2.msg, 'error');
        return true;
      }
    }
  });
};

const goToBankList = () => {
  navigate({ url: '/subcontract/person/collectAccount/bankList' });
};

const goToBankBranchList = () => {
  navigate({ url: '/subcontract/person/collectAccount/bankBranchList?bankCode=' + data.bankCode });
};

const submitInfo = () => {
  const rules = [
    {
      key: 'fullName',
      msg: '请输入姓名',
    },
    {
      key: 'phone',
      msg: '请输入手机号',
      pattern: [{ reg: /(^1(3|4|5|6|7|8|9)\d{9}$)|(^0\d{2,3}-?\d{7,8}$)/, msg: '手机号格式错误' }],
    },
    {
      key: 'idCard',
      msg: '请输入身份证号',
      pattern: [{ reg: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, msg: '身份证格式错误' }],
    },
    {
      key: 'bankCode',
      msg: '请选择银行',
    },
    {
      key: 'branchCode',
      msg: '请选择银行支行',
    },
    {
      key: 'cardNo',
      msg: '请输入银行卡号',
    },
  ];
  if (!validate(rules, data)) return;
  showModal('确定提交吗？', {
    showCancel: true,
    success: (resM) => {
      if (resM.confirm) {
        const { fullName, phone, idCard, cardNo, bankCode, branchCode, bankName, branchName, bankCardFront, bankCardBack, idCardFront, idCardBack, ymAccountId, otherYmAccountId, userId } = data;
        const params = {
          userId,
          fullName,
          phone,
          idCard,
          bankCode,
          bankName,
          branchCode,
          branchName,
          bankCardFront,
          bankCardBack,
          idCardFront,
          idCardBack,
          cardName: fullName,
          cardNo,
          cardType: 2,
          defaultFlag: 1,
          userType: 3,
          ...(ymAccountId && { ymAccountId }), // 条件赋值
          ...(otherYmAccountId && { otherYmAccountId }), // 条件赋值
        };
        UserRequest.SetCollectAccountInfo({
          ...params,
          hasLoading: true,
        }).then((res) => {
          if (res.status === 0) {
            showToast('提交成功，请等待审核');
            setTimeout(() => {
              navigate({ url: '', type: 'navigateBack' });
            }, 1500);
          }
        });
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.img-size {
  margin-top: 10rpx;
  width: 320rpx;
  height: 200rpx;
}
</style>
